package com.wxyzz.satserver.component;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class OnlineUserManager {
    //考虑线程安全
    private ConcurrentHashMap<Integer, WebSocketSession> sessions = new ConcurrentHashMap<>();

    //1.用户上线,给这个哈希表中插入键值对
    public void online(int userId,WebSocketSession session){
        if(sessions.get(userId) != null){
            System.out.println("[" +userId+
                    "] 已经被登录,登录失败");
            return;
        }
        sessions.put(userId,session);
        System.out.println("[" +userId +
                "]上线");
    }
    //2.用户下线,针对哈希表进行删除元素
    public void offline(int userId,WebSocketSession session){
        WebSocketSession existSession = sessions.get(userId);
        if(existSession == session){
            sessions.remove(userId);
            System.out.println("[" +userId+
                    "]下线");
        }
    }
    //3.根据userId 获取到WebSocketSession
    public WebSocketSession getSession(int userId){
        return sessions.get(userId);
    }

}
